package com.weijian.dal.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.weijian.dal.entity.CourseLike;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 课程点赞Mapper
 * 使用原生SQL实现查询操作
 */
@Mapper
public interface CourseLikeMapper extends BaseMapper<CourseLike> {

    /**
     * 获取点赞课程的用户ID列表
     */
    @Select("SELECT user_id FROM course_likes WHERE course_id = #{courseId} AND deleted = 0 ORDER BY create_time DESC")
    List<Long> selectLikedUserIds(@Param("courseId") Long courseId);

    /**
     * 获取用户点赞的课程ID列表
     */
    @Select("SELECT course_id FROM course_likes WHERE user_id = #{userId} AND deleted = 0 ORDER BY create_time DESC")
    List<Long> selectLikedCourseIds(@Param("userId") Long userId);

    /**
     * 获取课程的点赞数量
     */
    @Select("SELECT COUNT(*) FROM course_likes WHERE course_id = #{courseId} AND deleted = 0")
    Long selectCourseLikeCount(@Param("courseId") Long courseId);

    /**
     * 获取用户点赞的课程数量
     */
    @Select("SELECT COUNT(*) FROM course_likes WHERE user_id = #{userId} AND deleted = 0")
    Long selectUserLikeCount(@Param("userId") Long userId);

    /**
     * 获取点赞数量排行榜
     */
    @Select("SELECT course_id FROM course_likes WHERE deleted = 0 GROUP BY course_id ORDER BY COUNT(*) DESC LIMIT #{limit}")
    List<Long> selectTopLikedCourses(@Param("limit") int limit);

    /**
     * 检查用户是否已点赞课程
     */
    @Select("SELECT COUNT(*) FROM course_likes WHERE user_id = #{userId} AND course_id = #{courseId} AND deleted = 0")
    int checkUserLikedCourse(@Param("userId") Long userId, @Param("courseId") Long courseId);

    /**
     * 获取用户的点赞关系详情
     */
    @Select("SELECT * FROM course_likes WHERE user_id = #{userId} AND course_id = #{courseId} AND deleted = 0")
    List<CourseLike> selectLikeDetail(@Param("userId") Long userId, @Param("courseId") Long courseId);

    /**
     * 批量获取用户的点赞状态
     */
    @Select({"<script>",
            "SELECT * FROM course_likes",
            "WHERE user_id = #{userId}",
            "AND course_id IN",
            "<foreach collection='courseIds' item='id' open='(' separator=',' close=')'>#{id}</foreach>",
            "AND deleted = 0",
            "</script>"})
    List<CourseLike> selectBatchLikeStatus(@Param("userId") Long userId, @Param("courseIds") List<Long> courseIds);
}